<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>点聚合</title>
    <style>
        *{
            padding: 0;
            margin: 0;
        }
        /* body,div{
            position: absolute;
            width: 100%;
            height: 100%;
        } */
        #allMap{
            position: absolute;
            width: 100%;
            height: 100%;
        }
        /*隐藏地图控件*/
        .anchorBL, .BMap_cpyCtrl {
            display: none;
        }
        /*地图聚合样式*/
        .bubble p {
            text-align: center;
            color: #fff;
        }
        .bubble .name {
            margin-top: 25px;
            font-size: 14px;
        }
        /*信息窗口样式*/
        .infoArea{
            font-size: 12px;
            padding: 4px;
            /* background-color: #fff; */
            border-radius: 2px;
            box-shadow: 0 10px 8px 0 rgba(0,0,0,.1);
        }
        .infoArea:after {
            content: '';
            position: absolute;
            border: 10px solid transparent;
            border-top: 10px solid #fff;
            bottom: -20px;
            left: 50%;
            transform: translate(-50%, 0);
        }
        .infoArea p{
            padding: 2px 10px;
        }
        .infoArea .name {
            height: 20px;
            line-height: 20px;
            font-weight: 800;
        }
        .bg-info-box{
            height: 24px;
            line-height: 24px;
            cursor: pointer;
            text-align: center;
            box-shadow: 0 1px 2px rgba(0,0,0,0.3);
        }
        .bg-info{
            min-width: 40px;
            box-sizing: content-box;
            transition: background-color .15s ease-in-out;
            padding: 0 3px;
            display: inline-block;
            background-color: #00a75b;
            border-radius: 2px;
            /* border: 1px solid #00a75b; */
            font-style: normal;
            
        }
        .bg-info:hover{
            background:#e4393c;
        }
        .lpTip>a {
            background: #059c49;
            color: #fff;
            opacity: .9;
        }
        .lpTip>a>p {
            background: #059c49;
            padding: 2px 5px;
            border-radius: 5px;
        }
        .lpTip>a>div {
            position: absolute;
            bottom: -11px;
            left: 44%;
            width: 0;
            height: 0;
            border-top: 6px solid #059c49;
            border-left: 6px solid transparent;
            border-right: 6px solid transparent;
            border-bottom: 6px solid transparent;
            opacity: .94;
            left: 50%;
            margin-left: -6px;
        }
    </style>
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=3.0&ak=wMDqy8mK3l4g9Ve15rt8Zk2wwfKlMhld"></script>
    <script src="http://api.map.baidu.com/library/GeoUtils/1.2/src/GeoUtils.js"></script>
    <!-- <script src="http://api.map.baidu.com/library/InfoBox/1.2/src/InfoBox_min.js"></script> -->
    <script type="text/javascript" src="js/InfoBox_min.js"></script>
    <script type="text/javascript" src="js/sz.js"></script>
    <script type="text/javascript" src="js/ns.js"></script>
    <script type="text/javascript" src="js/kjy.js"></script>
</head>
<body>
    <!--地图-->
    <div id="allMap"></div>
    <script>
        // https://blog.csdn.net/tjj3027/article/details/81015138 百度地图缩放级别对照
        let noZoomend = true
        let map = new BMap.Map("allMap", {enableMapClick: false, minZoom: 11, maxZoom: 18});
        // enableMapClick是否开启底图可点功能，默认启用
        map.enableScrollWheelZoom(true);//开启鼠标滚轮缩放功能。仅对PC上有效
        map.disableInertialDragging();//禁用地图惯性拖拽
        window.labelData=[];//存数点位数据
        window.map = initMap(12, true);//初始化地图对象
        window.lastInfoBox = null; //定义最近打开的地图信息窗体
        window.pointArray = [];//行政区划点位集合
        //左上角，添加默认缩放平移控件
        var top_left_control = new BMap.ScaleControl({anchor: BMAP_ANCHOR_TOP_LEFT});// 左上角，添加比例尺
        map.addControl(top_left_control);
        

        function initMap(jLevel,initPt,lngLat) {
            let initPoint = new BMap.Point(113.95565020448,22.552100509472);//科技园中心点

            // getBounds() 返回地图可视区域，以地理坐标表示
            setTimeout(()=>{
                let initBounds = map.getBounds()
                // getSouthWest()    Point    返回矩形区域的西南角--左下角
                // getNorthEast()    Point    返回矩形区域的东北角--右上角
                // console.log('map.getBounds()',initBounds,initBounds.getSouthWest(),initBounds.getNorthEast())
                if(initBounds.getSouthWest().lng) {
                    /*获取当前地图可视区域内的数据*/
                    let abc = new BMap.Polygon([
                        new BMap.Point(initBounds.getSouthWest().lng, initBounds.getSouthWest().lat),
                        new BMap.Point(initBounds.getSouthWest().lng, initBounds.getNorthEast().lat),
                        new BMap.Point(initBounds.getNorthEast().lng, initBounds.getNorthEast().lat),
                        new BMap.Point(initBounds.getNorthEast().lng, initBounds.getSouthWest().lat)
                    ], {strokeColor:"blue", strokeWeight:2, strokeOpacity:0.1}); //建立多边形覆盖物
                    map.addOverlay(abc);
                }
            },30)
            
            if(!initPt){
                // getCenter()    返回矩形的中心点
                let cp = map.getCenter();
                initPoint = new BMap.Point(cp.lng, cp.lat);
            }
            if(initPt && lngLat){
                noZoomend = false
                initPoint = new BMap.Point(lngLat.lng, lngLat.lat);
            }
            // console.log('lngLat',lngLat)
            map.centerAndZoom(initPoint, jLevel);//初始化
            // 点击缩放之后放开缩放事件
            noZoomend = true

            let resData = {}
            console.log("jLevel:"+jLevel)
            if(jLevel <= 12) {
                resData = szData
            }
            if(jLevel > 12 && jLevel < 16) {
                resData = nsData
            }
            if(jLevel >= 16) {
                resData = kjyData
            }
            addMarker(resData)
        }

        //监听地图级别缩放事件，当级别为11时默认加载集合点，扩大级别时显示详细点位数据
        map.addEventListener("zoomend", function () {
            if(!noZoomend){
                return
            }
            
            // zoomend 地图更改缩放级别结束时触发触发此事件
            let zoomLevel = map.getZoom(); //获取地图缩放级别
            initMap(zoomLevel);
        });

        //停止拖拽地图时触发
        map.addEventListener("dragend", function () {
            // let initBounds = map.getBounds()
            console.log('dragend')
            let zoomLevel = map.getZoom(); //获取地图缩放级别
            initMap(zoomLevel);
        });

        //根据行政区划绘制聚合点位
        function addMarker(resData) {
            map.clearOverlays();//清除地图上所有覆盖物
            labelData = []; //清空点位信息
            //模拟数据---这里应该是请求接口后返回的数据
            let szDatas = resData.data.list
            //为了提高百度地图性能，本篇例子点位全用label来加载点位
            for (let index in szDatas) {
                (function(i){
                    let data = szDatas[i]
                    // Point(lng: 地理经度, lat: Number)    以指定的经度和纬度创建一个地理点坐标
                    let point = new BMap.Point(data.longitude, data.latitude);
                    //自定义label样式
                    if(!data.border){
                        getAllLabel(data)
                        return
                    }
                    let tpl = `<div class="bubble bubble-1" data-longitude="${data.longitude}"` +
                        ` data-latitude="${data.latitude}" data-id="${data.id}" data-border="${data.border}">` +
                        `<p class="name" title="${data.name}">${data.name}</p>` +
                        `<p title="${data.unit_price}">${(data.unit_price/10000).toFixed(1)}万</p>` +
                        `<p><span class="count">${data.count}</span>个楼盘</p>` +
                        `</div>`;
                    let myLabel = new BMap.Label(tpl,{
                        position: point, //label 在此处添加点位位置信息
                        offset: new BMap.Size(-46, -46)
                    });
                    myLabel.setStyle({
                        width: "92px",  //宽
                        height: "92px", //高度
                        border: "0",  //边
                        background: "rgba(84,144,244,.9)",    //背景颜色
                        borderRadius:"50%",
                        cursor: "pointer"
                    });
                    // myLabel.setTitle(data.name);
                    map.addOverlay(myLabel);//添加点位
                    // 当鼠标悬停在label上时显示行政区划边界
                    myLabel.addEventListener("mouseover", function (e) {
                        myLabel.setStyle({background:"rgba(241,80,68,.9)"}); //修改覆盖物背景颜色
                        // console.log('myLabel',myLabel.ba.children[0].dataset)
                        // var regionName = myLabel.getTitle();
                        // getBoundary(myLabel.ba.children[0].dataset.border);
                        getBoundary(data.border)
                    });
                    // 当鼠标离开时在删除边界折线数据
                    myLabel.addEventListener("mouseout", function () {
                        myLabel.setStyle({background:"rgba(84,144,244,.9)"}); //修改覆盖物背景颜色
                        if (window.ply) {
                            let polyPathArray = new Array();
                            window.ply.setPath(polyPathArray);
                            map.removeOverlay(ply);//清除折线数据
                        }
                    });
                    myLabel.addEventListener("click", function (e) {
                        //单击获取点击的经纬度
                        // alert(e.point.lng + "," + e.point.lat);
                        let zoomLevel = map.getZoom(); //获取地图缩放级别
                        if(zoomLevel <= 12) {
                            initMap(13,true,e.point);
                        }
                        if(zoomLevel > 12 && zoomLevel < 16) {
                            initMap(16,true,e.point);
                        }
                        
                    })
                })(index)
            }
            //加载可视范围点
            if(labelData.length) {
                // for(var i = 0; i < labelData.length; i ++){
                //     map.addOverlay(labelData[i])
                // }
                addViewLabel(labelData)
            }
            
        }


        //根据行政区划绘制边界
        function getBoundary(regionBorder) {
            if (!window.ply) {
                window.ply = new BMap.Polygon(regionBorder, {
                    strokeWeight: 2,
                    strokeColor: "rgb(66, 133, 244)",
                    fillColor: "rgba(53, 126, 244,0.1)"
                }); //建立多边形覆盖物
                map.addOverlay(ply);  //添加覆盖物
            } else {
                window.ply.setPath(regionBorder);
                map.addOverlay(ply);  //添加覆盖物
            }
            ply.enableMassClear();//允许覆盖物在map.clearOverlays方法中被清除
            pointArray = pointArray.concat(ply.getPath());
        }


        //绘制详细楼盘点位信息
        function getAllLabel(data) {
            map.clearOverlays();
            //模拟点位数据
            var point = new BMap.Point(data.longitude, data.latitude);
            var htm = `<div id="pcnewmap_C04_04" newcode="3110068740" class="lpTip lpTip2"><a class=""><p><b>${(data.unit_price/10000).toFixed(1)}</b>万元/㎡<em>|</em>${data.count}套<span><em>|</em>${data.name}</span></p> <div></div></a></div>`
            // let posInfo = `<p class="bg-info-box"><i class="bg-info"></i></p>`
            var myLabel = new BMap.Label(htm, {
                    position: point, //label 在此处添加点位位置信息
                    offset: new BMap.Size(-12, -15)
                });
            myLabel.setStyle({
                border: "0",  //边
                backgroundColor: "transparent"
            });
            // myLabel.setTitle(data.name);
            labelData.push(myLabel);
    //            map.addOverlay(myLabel);
            //信息窗口模板
            let tpl = `<div class="infoBox" data-longitude="${data.longitude}"` +
                        ` data-latitude="${data.latitude}" data-id="${data.id}">` +
                        `<div class='infoArea'><p class='name'>${data.name}</p><p class='num'>均价<span class='red'>${(data.unit_price/10000).toFixed(1)}</span>万元/m3</p></div>` +
                        `<i class='arrow'><i class='arrow-i'></i></i></div>`;
            var infoBox = new BMapLib.InfoBox(map, tpl, {
                boxStyle: {
                    width: "160px",
                    minHeight: "50px",
                    marginBottom: "30px",
                    backgroundColor: "#fff"
                },
                closeIconMargin: "15px 10px 4px 4px",
                closeIconUrl: "https://image1.ljcdn.com/hdic-resblock/1b7bed8e-b8e1-4187-8cc3-f54c46a625f3.jpg.280x210.jpg",
                enableAutoPan: false,
                align: INFOBOX_AT_TOP
            });
            //鼠标点击时打开新标签并关闭上一个标签内容
            myLabel.addEventListener("mouseover", function () {
                myLabel.setStyle({zIndex: "0"});
                if (window.lastInfoBox) {
                    //判断上一个窗体是否存在，若存在则执行close
                    window.lastInfoBox.close();
                }
                window.lastInfoBox = infoBox;
                infoBox.open(point);
            });
            // 当鼠标离开时再删除边界折线数据
            myLabel.addEventListener("mouseout", function () {
                myLabel.setStyle({zIndex: "-1"});
            });
            //鼠标点击时标签一直存在
            myLabel.addEventListener("click", function () {
                window.lastInfoBox=null;
                infoBox.open(point);
            });
        }


        //根据地图视野动态加载数据，当数据多时此方法用来提高地图加载性能
        //由于此篇模拟点位数据较少，视野加载不明显，当数据多时可直观感觉
        function addViewLabel(labels) {
            // console.log('addViewLabel',labels)
            // console.log('map.getBounds()',map.getBounds())
            map.clearOverlays();
            for(var i = 0; i < labels.length; i ++){
                // getBounds() 返回地图可视区域，以地理坐标表示
                // BMapLib.GeoUtils.isPointInRect判断点是否在矩形内  需要引入GeoUtils_min.js
                var result = BMapLib.GeoUtils.isPointInRect(labels[i].point, map.getBounds());
                if(result == true) {
                    map.addOverlay(labels[i])
                } else{
                    map.removeOverlay(labels[i]);
                }
            }
        }
    </script>
</body>
</html>